package com.zx.ms.test.springcloud.hystrixconsumer.service;

import com.netflix.hystrix.*;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

public class UserCommand extends HystrixCommand<String> {

    private RestTemplate restTemplate;
    private Long id;

    public UserCommand(Setter setter,RestTemplate restTemplate,Long id){

        super(setter);
        this.restTemplate = restTemplate;
        this.id = id;

    }

    public UserCommand(RestTemplate restTemplate,Long id){

//        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName"))
//                .andCommandKey(HystrixCommandKey.Factory.asKey("CommandKeyName")));
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("CommandKeyName"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("ThreadPoolKey")));
        this.restTemplate = restTemplate;
        this.id = id;

    }

    @Override
    protected String run() throws Exception {
       // return restTemplate.getForObject("http://USER-SERVICE/users/{1}",String.class,id);
        return restTemplate.getForObject("http://HELLO-DEV/hello",String.class);
    }

    /**
     * 自定义降级异常处理
     * @return
     */
    @Override
    protected String getFallback() {
        Throwable e = getExecutionException();
        System.out.println(e.getMessage());
        return "u a error!";
    }

    /**
     * 重写设置缓存
     * @return
     */
    @Override
    protected String getCacheKey() {
        return String.valueOf(id);
    }

//    /**
//     * 清楚缓存 需要手动调用
//     * @param id
//     */
//    public static void flushCache(Long id){
//        HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("CommandKeyName")
//                , HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
//    }

}
